import asyncio
import datetime
import uvicorn
from fastapi import FastAPI, Body

# import apcheduler
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor
from apscheduler.triggers.cron import CronTrigger

app = FastAPI(title='fast-api')

scheduler = None


@app.on_event('startup')
def init_scheduler():
    """初始化"""

    jobstores = {
        # SQLAlchemyJobStore指定存储链接
        'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
    }
    executors = {
        'default': {'type': 'threadpool', 'max_workers': 20},  # 最大工作线程数20
        'processpool': ProcessPoolExecutor(max_workers=5)  # 最大工作进程数为5
    }

    global scheduler
    scheduler = AsyncIOScheduler()
    scheduler.configure(jobstores=jobstores)
    print("启动调度器...")
    scheduler.start()
    # 添加一个coroutine执行，结果很不理想...
    # scheduler.add_job(print_time, 'interval', seconds=3, args=('test',))  # 没问题
    scheduler.add_job(tick, 'interval', seconds=3)  # 有问题


async def tick():
    print('Tick! The time is: %s' % datetime.datetime.now())
    await asyncio.sleep(1)


@app.post('/add-job')
async def add_job(job_id: str = Body(...), cron: str = Body(...)):
    """添加job"""
    scheduler.add_job(id=job_id, func=print_time, args=(
        job_id, ), trigger=CronTrigger.from_crontab(cron))
    return {"msg": "success!"}


@app.post('/remove-job')
async def remove_job(job_id: str = Body(..., embed=True)):
    """移除job"""
    scheduler.remove_job(job_id)
    return {"msg": "success!"}


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=5566)
